<template>
  <div class="article-edit">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="back-btn">
        <router-link to="/admin/articles" class="admin-btn">
          <i class="icon-back"></i> 返回列表
        </router-link>
      </div>
      <div class="header-title">
        <h2>{{ isEditMode ? '编辑文章' : '新建文章' }}</h2>
      </div>
      <div class="action-btns">
        <button class="admin-btn" @click="saveAsDraft">保存草稿</button>
        <button class="admin-btn admin-btn-primary" @click="publishArticle">{{ isEditMode ? '更新文章' : '发布文章' }}</button>
      </div>
    </div>

    <!-- 加载中提示 -->
    <div v-if="loading" class="loading-container">
      <div class="loading-spinner"></div>
      <p>正在加载文章数据...</p>
    </div>

    <!-- 错误提示 -->
    <div v-else-if="error" class="error-container">
      <p class="error-message">{{ error }}</p>
      <button class="admin-btn" @click="retryLoading">重试</button>
    </div>

    <div v-else class="article-form">
      <!-- 表单区域 -->
      <div class="form-section">
        <div class="form-group">
          <label for="article-title" class="form-label">文章标题 <span class="required">*</span></label>
          <input 
            type="text" 
            id="article-title" 
            v-model="article.title" 
            class="admin-form-input" 
            :class="{ 'input-error': validationErrors.title }"
            placeholder="请输入文章标题"
          />
          <div v-if="validationErrors.title" class="error-message">{{ validationErrors.title }}</div>
        </div>

        <div class="form-row">
          <div class="form-group half">
            <label for="article-category" class="form-label">文章分类 <span class="required">*</span></label>
            <select 
              id="article-category" 
              v-model="article.category" 
              class="admin-form-input" 
              :class="{ 'input-error': validationErrors.category }"
            >
              <option value="">请选择分类</option>
              <option value="news">新闻动态</option>
              <option value="guide">使用指南</option>
              <option value="knowledge">环保知识</option>
              <option value="event">活动公告</option>
            </select>
            <div v-if="validationErrors.category" class="error-message">{{ validationErrors.category }}</div>
          </div>

          <div class="form-group half">
            <label for="article-author" class="form-label">作者 <span class="required">*</span></label>
            <input 
              type="text" 
              id="article-author" 
              v-model="article.author" 
              class="admin-form-input" 
              :class="{ 'input-error': validationErrors.author }"
              placeholder="请输入作者姓名"
            />
            <div v-if="validationErrors.author" class="error-message">{{ validationErrors.author }}</div>
          </div>
        </div>

        <div class="form-group">
          <label class="form-label">文章封面</label>
          <div class="cover-upload">
            <div v-if="article.cover" class="cover-preview">
              <img :src="article.cover" alt="文章封面预览" />
              <button class="remove-cover" @click="removeCover">
                <i class="icon-delete"></i>
              </button>
            </div>
            <div v-else class="upload-placeholder" @click="triggerFileUpload">
              <i class="icon-upload"></i>
              <span>点击上传封面图片</span>
              <input 
                type="file" 
                ref="fileInput" 
                style="display: none" 
                accept="image/*" 
                @change="handleFileUpload" 
              />
            </div>
          </div>
          <div class="upload-hint">推荐尺寸: 1200 x 630 像素，最大文件大小: 2MB</div>
        </div>

        <div class="form-group">
          <label for="article-content" class="form-label">文章内容 <span class="required">*</span></label>
          <textarea 
            id="article-content" 
            v-model="article.content" 
            class="admin-form-input content-editor" 
            :class="{ 'input-error': validationErrors.content }"
            placeholder="请输入文章内容（支持Markdown格式）"
            rows="15"
          ></textarea>
          <div v-if="validationErrors.content" class="error-message">{{ validationErrors.content }}</div>
        </div>

        <div class="form-row">
          <div class="form-group half">
            <label for="article-tags" class="form-label">标签 (用逗号分隔)</label>
            <input 
              type="text" 
              id="article-tags" 
              v-model="article.tags" 
              class="admin-form-input" 
              placeholder="例如: 环保,低碳,节能"
            />
          </div>
          
          <div class="form-group half">
            <label for="article-status" class="form-label">状态 <span class="required">*</span></label>
            <select 
              id="article-status" 
              v-model="article.status" 
              class="admin-form-input" 
              :class="{ 'input-error': validationErrors.status }"
            >
              <option value="draft">草稿</option>
              <option value="published">已发布</option>
              <option value="archived">已归档</option>
            </select>
            <div v-if="validationErrors.status" class="error-message">{{ validationErrors.status }}</div>
          </div>
        </div>
      </div>

      <!-- 表单底部操作区 -->
      <div class="form-actions">
        <button class="admin-btn" @click="cancelEdit">取消</button>
        <div>
          <button class="admin-btn" @click="saveAsDraft" style="margin-right: 10px">保存草稿</button>
          <button class="admin-btn admin-btn-primary" @click="publishArticle">{{ isEditMode ? '更新文章' : '发布文章' }}</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'ArticleEdit',
  data() {
    return {
      isEditMode: false,
      articleId: null,
      loading: false,
      error: null,
      article: {
        title: '',
        category: '',
        author: '',
        content: '',
        cover: null,
        tags: '',
        status: 'draft',
        publishedAt: ''
      },
      validationErrors: {}
    }
  },
  created() {
    // 检查是否是编辑模式
    this.articleId = this.$route.params.id;
    this.isEditMode = !!this.articleId;
    
    if (this.isEditMode) {
      this.fetchArticleData();
    } else {
      // 新建文章时设置默认值
      this.article.author = localStorage.getItem('adminName') || '系统管理员';
    }
  },
  methods: {
    fetchArticleData() {
      this.loading = true;
      this.error = null;
      
      // 模拟API请求延迟
      setTimeout(() => {
        // 这里应该是实际的API调用
        // 现在使用模拟数据
        if (this.articleId === '1') {
          this.article = {
            id: 1,
            title: '每日低碳生活：5个简单但有效的节能方法',
            author: '环保小编',
            category: 'knowledge',
            status: 'published',
            cover: 'https://via.placeholder.com/1200x630',
            content: '# 每日低碳生活指南\n\n在当今气候变化日益严重的情况下，每个人都可以通过简单的日常习惯改变来减少碳足迹。\n\n## 1. 减少用电量\n\n- 不使用电器时拔掉插头\n- 使用LED节能灯泡\n- 充分利用自然光\n\n## 2. 节约用水\n\n- 洗澡时间控制在5分钟以内\n- 修复漏水的水龙头\n- 收集雨水用于浇花\n\n## 3. 绿色出行\n\n- 短距离出行选择步行或骑行\n- 多使用公共交通工具\n- 考虑拼车出行\n\n## 4. 减少食物浪费\n\n- 合理购买食材，避免过量\n- 学会食物保存方法\n- 尝试堆肥\n\n## 5. 减少塑料使用\n\n- 自带购物袋\n- 使用可重复使用的水瓶\n- 拒绝一次性塑料制品',
            tags: '环保,节能,低碳,生活方式',
            publishedAt: '2023-05-15 10:30',
            views: 2456
          };
        } else {
          // 如果找不到文章，显示错误信息
          this.error = '找不到该文章或已被删除';
        }
        
        this.loading = false;
      }, 1000);
    },
    triggerFileUpload() {
      this.$refs.fileInput.click();
    },
    handleFileUpload(event) {
      const file = event.target.files[0];
      if (!file) return;
      
      // 检查文件类型和大小
      if (!file.type.match('image.*')) {
        alert('请上传图片文件');
        return;
      }
      
      if (file.size > 2 * 1024 * 1024) {
        alert('图片大小不能超过2MB');
        return;
      }
      
      // 模拟上传过程，实际应该调用API上传
      const reader = new FileReader();
      reader.onload = (e) => {
        this.article.cover = e.target.result;
      };
      reader.readAsDataURL(file);
    },
    removeCover() {
      this.article.cover = null;
      // 清除文件输入值，允许重新选择同一文件
      if (this.$refs.fileInput) {
        this.$refs.fileInput.value = '';
      }
    },
    validateForm() {
      let isValid = true;
      this.validationErrors = {};
      
      if (!this.article.title.trim()) {
        this.validationErrors.title = '请输入文章标题';
        isValid = false;
      }
      
      if (!this.article.category) {
        this.validationErrors.category = '请选择文章分类';
        isValid = false;
      }
      
      if (!this.article.author.trim()) {
        this.validationErrors.author = '请输入作者姓名';
        isValid = false;
      }
      
      if (!this.article.content.trim()) {
        this.validationErrors.content = '请输入文章内容';
        isValid = false;
      }
      
      if (!this.article.status) {
        this.validationErrors.status = '请选择文章状态';
        isValid = false;
      }
      
      return isValid;
    },
    saveAsDraft() {
      // 保存为草稿时只需要有标题
      if (!this.article.title.trim()) {
        this.validationErrors = {
          title: '请至少输入文章标题'
        };
        return;
      }
      
      this.article.status = 'draft';
      this.saveArticle();
    },
    publishArticle() {
      if (!this.validateForm()) {
        alert('请完善文章信息');
        return;
      }
      
      if (this.article.status !== 'published') {
        this.article.status = 'published';
      }
      
      this.saveArticle();
    },
    saveArticle() {
      // 这里应该调用API保存文章
      console.log('保存文章:', this.article);
      
      // 模拟保存成功
      alert(this.isEditMode ? '文章更新成功！' : '文章保存成功！');
      this.$router.push('/admin/articles');
    },
    cancelEdit() {
      // 放弃编辑，返回列表页
      if (this.isEditMode) {
        const confirmed = confirm('确定要放弃编辑吗？未保存的内容将会丢失。');
        if (confirmed) {
          this.$router.push('/admin/articles');
        }
      } else {
        this.$router.push('/admin/articles');
      }
    },
    retryLoading() {
      if (this.isEditMode) {
        this.fetchArticleData();
      } else {
        this.error = null;
      }
    }
  }
}
</script>

<style scoped>
.article-edit {
  width: 100%;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.header-title h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 500;
}

.icon-back {
  margin-right: 5px;
}

.action-btns {
  display: flex;
  gap: 10px;
}

.loading-container, .error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px;
  text-align: center;
}

.loading-spinner {
  border: 4px solid rgba(0, 0, 0, 0.1);
  border-radius: 50%;
  border-top: 4px solid #1890ff;
  width: 40px;
  height: 40px;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.error-message {
  color: #ff4d4f;
  margin-bottom: 16px;
}

.article-form {
  background-color: white;
  border-radius: 4px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.form-section {
  padding: 24px;
}

.form-group {
  margin-bottom: 24px;
}

.form-row {
  display: flex;
  gap: 24px;
  margin-bottom: 24px;
}

.form-group.half {
  flex: 1;
  margin-bottom: 0;
}

.form-label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: rgba(0, 0, 0, 0.85);
}

.required {
  color: #ff4d4f;
  margin-left: 4px;
}

.content-editor {
  resize: vertical;
  min-height: 300px;
  font-family: monospace;
}

.input-error {
  border-color: #ff4d4f;
}

.error-message {
  font-size: 14px;
  color: #ff4d4f;
  margin-top: 4px;
}

.cover-upload {
  margin-top: 8px;
}

.upload-placeholder {
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  padding: 32px;
  text-align: center;
  color: #999;
  cursor: pointer;
  transition: border-color 0.3s;
}

.upload-placeholder:hover {
  border-color: #40a9ff;
  color: #40a9ff;
}

.icon-upload {
  font-size: 24px;
  margin-bottom: 8px;
  display: block;
}

.upload-hint {
  font-size: 12px;
  color: #999;
  margin-top: 8px;
}

.cover-preview {
  position: relative;
  width: 100%;
  max-width: 300px;
  border-radius: 4px;
  overflow: hidden;
}

.cover-preview img {
  width: 100%;
  display: block;
}

.remove-cover {
  position: absolute;
  top: 8px;
  right: 8px;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  border: none;
  border-radius: 50%;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: background-color 0.3s;
}

.remove-cover:hover {
  background-color: rgba(0, 0, 0, 0.7);
}

.form-actions {
  padding: 16px 24px;
  background-color: #f5f5f5;
  border-top: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

/* 图标样式 */
.icon-back:before { content: "←"; }
.icon-delete:before { content: "×"; }
.icon-upload:before { content: "↑"; }
</style> 